﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.IO;

namespace MvcWechat.Common
{
    public class ManagerJson
    {
        //接收到前端的json
        public static string ToJson(Stream stream)
        {
            stream.Seek(0, SeekOrigin.Begin);
            string json = new StreamReader(stream).ReadToEnd();
            return json;
        }

///////////////////////////////////后加，不知是否有用//////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// 序列化Json
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string Serialize(object source)
        {
            return JsonConvert.SerializeObject(source, GetJsonSetting());
        }

        /// <summary>
        /// 反序列化Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string json) where T : class, new()
        {
            return JsonConvert.DeserializeObject(json, typeof(T), GetDeserializeJsonSetting()) as T;
        }

        /// <summary>
        /// 反序列化Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static object Deserialize(string json, Type targetType)
        {
            return JsonConvert.DeserializeObject(json, targetType, GetDeserializeJsonSetting());
        }

        private static JsonSerializerSettings GetJsonSetting()
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
            JsonSerializerSettings setting = new JsonSerializerSettings()
            {
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling = NullValueHandling.Ignore,
            };
            setting.Converters.Add(timeConverter);
            return setting;
        }

        public static JsonSerializerSettings GetDeserializeJsonSetting()
        {
            JsonSerializerSettings setting = new JsonSerializerSettings()
            {
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling = NullValueHandling.Ignore
            };
            setting.Error = new EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>((o, e) =>
            {
                //记录日志
                e.ErrorContext.Handled = true;
            });
            return setting;
        }
    }
     
}